package com.wunong.smart.collection.starter.infrastructure.converter;

import com.wunong.smart.collection.client.enums.CollectionStatusEnum;
import com.wunong.smart.collection.domain.model.CollectionDomain;
import com.wunong.smart.collection.starter.infrastructure.po.CollectionPO;
import com.wunong.smart.domain.platform.common.BizSource;
import com.wunong.smart.domain.platform.common.ICode;
import com.wunong.smart.domain.platform.entify.User;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author create by zealot.zt
 */
public final class CollectionConverter {

    public static CollectionDomain toDomain(CollectionPO po) {
        if (po == null) {
            return null;
        }

        CollectionDomain domain = CollectionDomain.of();
        domain.init(po);

        if (Objects.nonNull(po.getBizId())) {
            domain.setSource(BizSource.of(po.getBizId(), po.getBizType()));
        }

        if (Objects.nonNull(po.getUserId())) {
            domain.setUser(User.of(po.getUserId(), po.getUserRole()));
        }

        domain.setCollectType(po.getCollectType());
        domain.setStatusEnum(CollectionStatusEnum.of(po.getStatus()));

        return domain;
    }

    public static List<CollectionDomain> toDomain(List<CollectionPO> pos) {
        if (CollectionUtils.isEmpty(pos)) {
            return null;
        }

        return pos.stream().map(CollectionConverter::toDomain).collect(Collectors.toList());
    }

    public static CollectionPO toPo(CollectionDomain domain) {
        if (domain == null) {
            return null;
        }

        CollectionPO po = CollectionPO.of();
        domain.init(po);

        BizSource source = domain.getSource();
        if (source != null) {
            po.setBizId(source.getBizId());
            po.setBizType(source.getBizType());
        }

        User user = domain.getUser();
        if (Objects.nonNull(user)) {
            po.setUserId(user.getIdLong());
            po.setUserRole(user.getRole());
        }

        po.setStatus(ICode.withCode(domain.getStatusEnum()));
        po.setCollectType(domain.getCollectType());

        return po;
    }
}
